package mao.proxy.cglib;

import mao.proxy.jdk.UserDao;
import mao.proxy.jdk.UserDaoImpl;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;


/**
 * @author Totoro
 * @date 2020/6/10
 * @explain:
 */
public class MyCglibProxy implements MethodInterceptor {

    public UserDao creatProxy(){
        Enhancer enhancer = new Enhancer();
        //设置base类
        enhancer.setSuperclass(UserDaoImpl.class);
        //设置回调。
        enhancer.setCallback(this);
        //产生继承类
        return (UserDao) enhancer.create();
    }

    @Override
    public Object intercept(Object proxy, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        if (method.getName().equals("getName")){
            Object o = methodProxy.invokeSuper(proxy, objects);
            System.out.println("日志记录");
            return o;
        }
        return methodProxy.invokeSuper(proxy,objects);
    }

    public static void main(String[] args) {
        //产生方法拦截器
        MyCglibProxy intercept = new MyCglibProxy();
        //产生代理
        UserDao userDao = intercept.creatProxy();
        userDao.getName(2);
    }
}
